package com.dingreading.cloud.subject.service.impl;

import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.dto.StaffRoleDto;
import com.dingreading.cloud.common.util.AccountUtil;
import com.dingreading.cloud.common.util.FileViewUtil;
import com.dingreading.cloud.subject.dto.CourseTrainDto;
import com.dingreading.cloud.subject.dto.CourseTrainTypesDto;
import com.dingreading.cloud.subject.entity.*;
import com.dingreading.cloud.subject.service.*;
import com.dingreading.cloud.subject.util.CdnUrlUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CourseTrainCommonServiceImpl implements CourseTrainCommonService {
    @Resource
    private CdnUrlUtil cdnUrlUtil;

    @Resource
    private CourseTrainTypesService courseTrainTypesService;
    @Resource
    private CourseTrainService courseTrainService;
    @Resource
    private StaffRolesService staffRolesService;
    @Resource
    private CourseTrainFileService courseTrainFileService;
    @Resource
    private CourseTrainLogService courseTrainLogService;
    @Resource
    private CourseTrainVideoLogService courseTrainVideoLogService;
    @Resource
    private StaffService staffService;


    @Override
    public R<Object> getList(String corpUid, String storeUid, String storeName, String staffUid, String staffName) {
        if (StringUtils.isBlank(corpUid) || StringUtils.isBlank(storeUid) || StringUtils.isBlank(staffUid))
            return R.fail("伙伴参数信息缺少");

        List<CourseTrainTypesDto> list = courseTrainTypesService.getMainType();

        StaffRoles staffRole = staffRolesService.getStoreUidAndStaffUid(storeUid, staffUid);
        String roles = staffRole.getRoles();
        if (null == staffRole || StringUtils.isBlank(roles))
            return R.fail("员工角色权限获取失败");
        List<String> roleList = Arrays.stream(StringUtils.split(roles, ","))
                .collect(Collectors.toList());
        StaffRoleDto staffRoleDto = AccountUtil.getStaffRoleV2(roleList);
        if (null == staffRoleDto)
            return R.fail("员工角色权限解析失败");
        int role = staffRoleDto.getRole();
        // 角色为4, 店助
        if (role == 4) {
            // 保留 list 中typeName为 销售 的数据
            list = list.stream().filter(item -> item.getTypeName().contains("销售"))
                    .collect(Collectors.toList());

        }
        // 角色为5, 导读组长 角色为6, 导读
        else if (role == 5 || role == 6) {
            list = list.stream().filter(item -> item.getTypeName().contains("导读"))
                    .collect(Collectors.toList());
        }
        List<Long> mainIds = list.stream().map(CourseTrainTypesDto::getId).distinct().collect(Collectors.toList());
        Map<Long, List<CourseTrainTypesDto>> typesDtoMap = courseTrainTypesService.getByMainIds(mainIds);
        for (CourseTrainTypesDto item : list) {
            List<CourseTrainTypesDto> courseTrainTypesDtoList = typesDtoMap.get(item.getId());
            item.setChildTypeList(courseTrainTypesDtoList);
        }
        return R.ok(list);
    }

    @Override
    public R<Object> getCourseTrain(String corpUid, String storeUid, String storeName, String staffUid, String staffName, String uid) {
        if (StringUtils.isBlank(uid))
            return R.fail("课程uid不能为空");

        CourseTrainDto courseTrainDto = courseTrainService.getByUid(uid);
        if (courseTrainDto == null) return R.fail("课程获取失败");
        if (courseTrainDto.getEnabled() != 1)
            return R.fail("课程已被禁用");
        return R.ok(courseTrainDto);
    }

    @Override
    public R<Object> getExamUrl(
            HttpServletRequest request, String corpUid, String storeUid, String storeName, String staffUid,
            String staffName, String typUid
    ) {
        if (StringUtils.isBlank(typUid))
            return R.fail("分类uid不能为空");

        CourseTrainTypes data = courseTrainTypesService.getByUid(typUid);
        if (data == null)
            return R.fail("未查询到分类");

        String username = staffService.getUsername(staffUid);

        CourseTrainTypes mainType = courseTrainTypesService.getById(data.getMainId());
        if (mainType == null)
            return R.fail("未查询到主分类");

        R<Object> duplicateDownload = courseTrainLogService.preventDuplicateDownload(storeUid, staffUid, data.getUid(), 3);
        if (R.isError(duplicateDownload))
            return duplicateDownload;

        R<String> r = cdnUrlUtil.getCdnUrl(request, data.getExamUrl());
        if (R.isError(r))
            return R.fail(r.getMsg());

        CourseTrainLog log = new CourseTrainLog();
        log.setAddStaffUid(staffUid);
        log.setAddStaffName(staffName);
        log.setCorpUid(corpUid);
        log.setStoreUid(storeUid);
        log.setStaffUid(staffUid);
        log.setUsername(username);
        log.setType(3);
        log.setMainTypeUid(mainType.getUid());
        log.setTypeUid(data.getUid());
        log.setLevelName(mainType.getTypeName() + " / " + data.getTypeName());
        courseTrainLogService.save(log);
        return R.ok(r.getData());
    }

    @Override
    public R<Object> getFileUrl(
            HttpServletRequest request, String corpUid, String storeUid, String storeName, String staffUid, String staffName,
            String uid, String fileUid
    ) {
        CourseTrainDto courseTrainDto = courseTrainService.getByUidNotFile(uid);
        if (courseTrainDto == null) {
            return R.fail("未查询到课程");
        }

        String username = staffService.getUsername(staffUid);

        String levelName = "";
        List<String> typeList = courseTrainDto.getTypeList();
        if (CollectionUtils.isNotEmpty(typeList)) {
            levelName = String.join(" / ", typeList);
        }

        CourseTrainFile courseTrainFile = courseTrainFileService.getByUid(fileUid);
        if (courseTrainFile == null) {
            return R.fail("未查询到文件");
        }

        int type = 1;
        int viewType = FileViewUtil.getViewType(courseTrainFile.getUrl());
        if (viewType == 1) {
            type = 1;
        } else if (viewType == 4) {
            type = 2;
        }

        R<String> r = cdnUrlUtil.getCdnUrl(request, courseTrainFile.getUrl());
        if (R.isError(r))
            return R.fail(r.getMsg());

        CourseTrainLog log = new CourseTrainLog();
        log.setAddStaffUid(staffUid);
        log.setAddStaffName(staffName);
        log.setCorpUid(corpUid);
        log.setStoreUid(storeUid);
        log.setStaffUid(staffUid);
        log.setUsername(username);
        log.setType(type);
        log.setMainTypeUid(courseTrainDto.getMainTypeUid());
        log.setTypeUid(courseTrainDto.getTypeUid());
        log.setLevelName(levelName);
        log.setCourseTrainUid(uid);
        log.setCourseTrainName(courseTrainDto.getName());
        log.setFileUid(fileUid);
        log.setFileName(courseTrainFile.getName());
        courseTrainLogService.save(log);
        return R.ok(r.getData());
    }


    @Override
    public R<Object> addVideoLog(
            HttpServletRequest request, String corpUid, String storeUid, String storeName, String staffUid, String staffName,
            String uid, String fileUid, String timeStamp, Integer startTime, Integer endTime
    ) {
        if (endTime <= 0) {
            return R.fail("结束时间要大于0");
        }
        int duration = endTime - startTime;
        if (duration < 10) {
            return R.fail("观看时间要大于10秒");
        }

        CourseTrainDto courseTrainDto = courseTrainService.getByUidNotFile(uid);
        if (courseTrainDto == null) {
            return R.fail("未查询到课程");
        }

        CourseTrainVideoLog log = new CourseTrainVideoLog();
        log.setAddStaffUid(staffUid);
        log.setAddStaffName(staffName);
        log.setCorpUid(corpUid);
        log.setStoreUid(storeUid);
        log.setStaffUid(staffUid);
        log.setCourseTrainUid(uid);
        log.setFileUid(fileUid);
        log.setTimeStamp(timeStamp);
        log.setStartTime(startTime);
        log.setEndTime(endTime);
        log.setDuration(duration);
        courseTrainVideoLogService.save(log);
        return R.ok();
    }

}
